from flask import Flask, send_file
from flask_socketio import SocketIO, emit
from flask_cors import CORS
from loguru import logger
import testpictostring
import base64
app = Flask(__name__,static_url_path='/')
CORS(app, supports_credentials=True)
socketio = SocketIO(app, cors_allowed_origins="*")
socketio.init_app(app)
which = 1
history = []
logger.add('file_{time}.log', format="{name} {level} {message}", level="INFO", rotation='5 MB', encoding='utf-8')
"""
对app进行一些路由设置
"""

"""
对socketio进行一些监听设置
"""


@app.route("/", methods=["GET"])
def home():
    return send_file("static/index.html")


@socketio.on("exam", namespace="/exam")
def msg_send(data):
    print(data)
    msg = data.get("msg")
    name = data.get("name")
    # 客户端接收服务端的回调消息
    global which
    print("my receive new msg:", data["msg"])
    logger.info(f'{data["name"]} {data["msg"]}')
    flag = True
    if data["msg"][0:8] == "pictostr":
       base64String = data["msg"][31:]
       print(base64String)
       img_rb = base64.b64decode(base64String)
       texts = testpictostring.get_string_rb(img_rb)
       searchPage = f"""<iframe style="display:block;width: 100%;height: 300px;" src="https://wap.baidu.com/s?word={texts}"></iframe>"""
       send_socket("获取到"+name+"的图片转字符串的请求。<br>"+ texts + searchPage,"系统")
       flag = False
    if flag:
       msg = msg.replace("script", "h1 style='color:red'")
       emit("response", {"code": "200", "msg": msg, "name": name}, broadcast=True)


def send_socket(data,name):
    data = data.replace("script", "h1 style='color:red'")
    emit("response", {"msg": data ,"name": name}, broadcast=True)


if __name__ == "__main__":
    socketio.run(app, debug=True, host="0.0.0.0", port=61222, ssl_context=('ssl/_.xiaotao2333.top_chain.crt', 'ssl/_.xiaotao2333.top_key.key'))
